﻿using System;
using System.IO;
using System.ServiceProcess;
using System.Windows.Forms;
using Manager.Configuration;
using Manager.Log;
using Manager.Properties;
using Manager.Tools.Dig;
using Manager.Tools.Host;
using Manager.Tools.NamedCheckconf;
using Manager.Tools.DnsSecKeygen;
using Manager.Tools.RndcConfgen;
using Manager.Tools.Rndc;

namespace Manager
{
    /// <summary>
    /// Main form for BIND management
    /// </summary>
    public partial class Main : Form
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Main"/> class.
        /// </summary>
        public Main()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Load event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Main_Load(object sender, EventArgs e)
        {
            serviceTimer.Start();
            SetStatusLabel();
        }

        /// <summary>
        /// Sets the status label to the current BIND service status.
        /// </summary>
        private void SetStatusLabel()
        {
            try
            {
                bindServiceController.Refresh();
                switch (bindServiceController.Status)
                {
                    case ServiceControllerStatus.ContinuePending:
                        bindStatusLabel.Text = "Operation pending...";
                        break;
                    case ServiceControllerStatus.PausePending:
                        bindStatusLabel.Text = "Operation pending...";
                        break;
                    case ServiceControllerStatus.Paused:
                        bindStatusLabel.Text = "Paused";
                        break;
                    case ServiceControllerStatus.Running:
                        bindStatusLabel.Text = "Running";
                        break;
                    case ServiceControllerStatus.StartPending:
                        bindStatusLabel.Text = "Operation pending...";
                        break;
                    case ServiceControllerStatus.StopPending:
                        bindStatusLabel.Text = "Operation pending...";
                        break;
                    case ServiceControllerStatus.Stopped:
                        bindStatusLabel.Text = "Stopped";
                        break;
                    default:
                        bindStatusLabel.Text = "Undefined";
                        break;
                }
            }
            catch
            {
                //TODO log error here
            }
        }

        /// <summary>
        /// Handles the Click event of the runButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void runButton_Click(object sender, EventArgs e)
        {
            try
            {
                RunBIND();
                SetStatusLabel();
            }
            catch(Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Could not start BIND service.", ex);
            }
        }

        /// <summary>
        /// Runs the BIND service.
        /// </summary>
        private void RunBIND()
        {
            if (bindServiceController.Status == ServiceControllerStatus.Stopped)
            {
                bindServiceController.Start();
            }
            else if (bindServiceController.Status == ServiceControllerStatus.Paused)
            {
                bindServiceController.Continue();
            }
        }

        /// <summary>
        /// Handles the Click event of the stopButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void stopButton_Click(object sender, EventArgs e)
        {
            try
            {
                StopBIND();
                SetStatusLabel();
            }
            catch(Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Could not stop BIND service.", ex);
            }
        }

        /// <summary>
        /// Stops the BIND service.
        /// </summary>
        private void StopBIND()
        {
                if (!bindServiceController.CanStop)
                {
                    return;
                }

                if (bindServiceController.Status == ServiceControllerStatus.Running ||
                    bindServiceController.Status == ServiceControllerStatus.Paused)
                {
                    bindServiceController.Stop();
                }
        }

        /// <summary>
        /// Handles the Click event of the exitToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// Handles the Tick event of the serviceTimer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void serviceTimer_Tick(object sender, EventArgs e)
        {
            SetStatusLabel();
        }

        /// <summary>
        /// Handles the TextChanged event of the bindStatusLabel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void bindStatusLabel_TextChanged(object sender, EventArgs e)
        {
            try
            {
                ShowBINDStatusBalloon();
            }
            catch(Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Could not show status balloon.", ex);
            }
        }

        /// <summary>
        /// Shows the BIND status balloon in system tray.
        /// </summary>
        private void ShowBINDStatusBalloon()
        {
            notifyIcon.BalloonTipTitle = "BIND status";
            notifyIcon.BalloonTipText = bindStatusLabel.Text;
            notifyIcon.ShowBalloonTip(500);
        }

        /// <summary>
        /// Handles the Click event of the startToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RunBIND();
            SetStatusLabel();
        }

        /// <summary>
        /// Handles the Click event of the stopToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StopBIND();
            SetStatusLabel();
        }

        /// <summary>
        /// Handles the Click event of the optionsToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                OptionsForm options = new OptionsForm();
                if (options.ShowDialog() == DialogResult.OK)
                {
                    string serviceMachineName = options.ServiceMachineName;
                    string serviceName = options.ServiceName;
                    string bINDDirectoryPath = options.BINDDirectoryPath;

                    Settings.Default.ServiceMachineName = serviceMachineName;
                    Settings.Default.ServiceName = serviceName;
                    Settings.Default.BindDirectoryPath = bINDDirectoryPath;
                    Settings.Default.Save();
                }
            }
            catch(Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Error occured while setting options", ex);
            }
        }

        /// <summary>
        /// Handles the Click event of the logToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void logToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Get log path from config file
                ConfigParser parser = new ConfigParser();
                parser.Path = Path.Combine(Settings.Default.BindDirectoryPath, @"etc\named.conf");
                parser.ReadLog();


                LogAnalyzerForm logForm = new LogAnalyzerForm();
                logForm.LogPath = parser.ParseLogging().File.Path;
                logForm.ShowDialog();
                logForm.Dispose();
            }
            catch(Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Error occured while parsing log file.", ex);
            }
        }

        /// <summary>
        /// Handles the Click event of the aboutToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm about = new AboutForm();
            about.ShowDialog();
        }

        /// <summary>
        /// Handles the Click event of the digToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void digToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DigForm dig = new DigForm();
                dig.ShowDialog();
            }
            catch (Exception ex)
            {
                ErrorHandler.ErrorHandler.ShowErrorMessage("Error occured while using Dig tool.", ex);
            }
        }

        /// <summary>
        /// Handles the FormClosed event of the Main control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.FormClosedEventArgs"/> instance containing the event data.</param>
        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            notifyIcon.Visible = false;
        }

        private void checkConfigurationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NamedCheckconfForm checkForm = new NamedCheckconfForm();
            checkForm.ShowDialog();
        }

        private void keyGeneratorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dnsSecKeygenForm dnssecForm = new dnsSecKeygenForm();
            dnssecForm.ShowDialog();
        }

        private void configurationGeneratorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RndcConfgenForm rndcConfForm = new RndcConfgenForm();
            rndcConfForm.ShowDialog();
        }

        private void hostToolStripMenuItem_Click(object sender, EventArgs e)
        {
            HostForm hostForm = new HostForm();
            hostForm.ShowDialog();
        }

        private void mdcToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            RndcForm rndcForm = new RndcForm();
            rndcForm.ShowDialog();
        }
    }
}
